'use client';

import * as React from 'react';

type ToastVariant = 'default' | 'destructive';

interface Toast {
  id: string;
  title?: string;
  description?: string;
  variant?: ToastVariant;
}

interface ToastContextType {
  toasts: Toast[];
  toast: (toast: Omit<Toast, 'id'>) => void;
  dismiss: (toastId: string) => void;
}

const ToastContext = React.createContext<ToastContextType | undefined>(undefined);

export function ToastProvider({ children }: { children: React.ReactNode }) {
  const [toasts, setToasts] = React.useState<Toast[]>([]);

  const toast = React.useCallback((toast: Omit<Toast, 'id'>) => {
    const id = Math.random().toString(36).substr(2, 9);
    setToasts((prev) => [...prev, { ...toast, id }]);
    
    setTimeout(() => {
      setToasts((prev) => prev.filter((t) => t.id !== id));
    }, 5000);
  }, []);

  const dismiss = React.useCallback((toastId: string) => {
    setToasts((prev) => prev.filter((t) => t.id !== toastId));
  }, []);

  const value = React.useMemo(() => ({
    toasts,
    toast,
    dismiss
  }), [toasts, toast, dismiss]);

  return React.createElement(
    ToastContext.Provider,
    { value },
    children,
    React.createElement(ToastContainer, { toasts, onDismiss: dismiss })
  );
}

function ToastContainer({ toasts, onDismiss }: { toasts: Toast[]; onDismiss: (id: string) => void }) {
  return React.createElement(
    'div',
    { className: 'fixed top-4 right-4 z-50 space-y-2' },
    toasts.map((toast) =>
      React.createElement(
        'div',
        {
          key: toast.id,
          className: `p-4 rounded-lg shadow-lg max-w-sm relative ${
            toast.variant === 'destructive'
              ? 'bg-red-500 text-white'
              : 'bg-white border border-gray-200'
          }`
        },
        toast.title && React.createElement('div', { className: 'font-semibold mb-1' }, toast.title),
        toast.description && React.createElement('div', { className: 'text-sm opacity-90' }, toast.description),
        React.createElement(
          'button',
          {
            onClick: () => onDismiss(toast.id),
            className: 'absolute top-2 right-2 text-gray-400 hover:text-gray-600'
          },
          '×'
        )
      )
    )
  );
}

export function useToast() {
  const context = React.useContext(ToastContext);
  if (!context) {
    throw new Error('useToast must be used within a ToastProvider');
  }
  return context;
}